package cn.nawang.ebeim.api.repository.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.nawang.ebeim.api.bean.ClassBean;
import cn.nawang.ebeim.api.comm.BaseQuery;
import cn.nawang.ebeim.api.comm.PageList;
import cn.nawang.ebeim.api.comm.Pages;
import cn.nawang.ebeim.api.domain.Ca;
import cn.nawang.ebeim.api.domain.StorageCloud;
import cn.nawang.ebeim.api.utils.RefectSql;

/**
 * @ClassName: CaQueryRepositoryImpl
 * @Description: ca资源层
 * @author 张建峰
 * @date 2015年8月7日14:56:49
 * @version v1.0
 */
@Repository
public class CaQueryRepositoryImpl extends BaseQuery{

  @Autowired
  private EntityManagerFactory entityManagerFactory;

  /**
   * @author 张建峰
   * @Description: 计算总记录数
   * @param @return
   * @date 2015年8月7日14:57:34
   *
   * @修改人 张建峰
   * @修改日期
   */
  public int countAllData() {
    int count = 0;
    String sql = "select count(*) from tb_ca";
    EntityManager em = entityManagerFactory.createEntityManager();
    try {
      Query query = em.createNativeQuery(sql);
      List objList = query.getResultList();
      if (objList != null && objList.size() > 0) {
        count = Integer.valueOf(objList.get(0).toString());
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      em.close();
    }
    return count;
  }

  /**
   * @author 张建峰
   * @Description: 根据sql查询count
   * @param @param sql
   * @param @return
   * @return int
   * @date 2015年8月7日14:57:59
   *
   * @修改人 张建峰
   * @修改日期
   */
  public int countData(String sql, List<Object> paramsList) {
    EntityManager em = entityManagerFactory.createEntityManager();
    int count=0;
    try {
      Query query = em.createQuery(sql);
      for (int i = 0; i < paramsList.size(); i++) {
        query.setParameter(i + 1, paramsList.get(i));
      }
      count = query.getResultList().size();
      return count;
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      em.close();
    }
    return count;
  }

  /**
   * @author 张建峰
   * @Description: 根据条件分页查询
   * @param @param t
   * @param @param page
   * @param @return
   * @return PageList
   * @date 2015年8月7日14:58:08
   *
   * @修改人 张建峰
   * @修改日期
   */
  public PageList findByCa(Ca t, Pages page) {
    PageList pl = null;
    String sql = "from Ca obj where '1'='1'";
    List<ClassBean> conditions = RefectSql.getClassBeans(t);
    List<Object> paramsList = new ArrayList<Object>();
    for (int i = 0; i < conditions.size(); i++) {
      ClassBean classBean = conditions.get(i);
      if (classBean.getContent() != null) {
        sql += " and obj." + classBean.getName() + "= ?";
        paramsList.add(classBean.getContent());
      }
    }

    int count = this.countData(sql, paramsList);
    page.setTotalRecord(count);
    page.setTotalPage((int) Math.ceil((count * 1.0) / page.getPageSize()));
    EntityManager em = entityManagerFactory.createEntityManager();
    try {
      Query query = em.createQuery(sql);
      query.setFirstResult(page.getStartPos());
      query.setMaxResults(page.getPageSize());
      for (int i = 0; i < paramsList.size(); i++) {
        query.setParameter(i + 1, paramsList.get(i));
      }
      List objList = query.getResultList();
      pl = new PageList();
      pl.setObjList(objList);
      pl.setPage(page);
      pl.setSuccess(true);
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      em.close();
    }
    return pl;
  }

  /**
   * @author 张建峰
   * @Description: 根据某个属性查询列表
   * @param @param property
   * @param @param value
   * @param @return
   * @return List<Ca>
   * @date 2015年8月7日14:58:39
   *
   * @修改人 张建峰
   * @修改日期
   */
  public List<Ca> findByParam(String property, Object value) {
    List objList = null;
    String sql = "from Ca obj where obj." + property + " = ?1";
    EntityManager em = entityManagerFactory.createEntityManager();
    try {
      Query query = em.createQuery(sql);
      query.setParameter(1, value);
      objList = query.getResultList();
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      em.close();
    }
    return objList;
  }

  /**
   * @author 张建峰
   * @Description: 根据终端id查询预警人员
   * @param @param terminalId
   * @param @return
   * @return List<Ca>
   * @date 2015年8月7日14:58:43
   *
   * @修改人 张建峰
   * @修改日期
   */
  public List<Ca> findByCustomerId(String customerId) {
    List<Ca> list = null;
    String sql =
        "select ca from Ca ca,CaCustomer cacu,Customer cu" + " where cu.id = cacu.customerId"
            + " and cacu.labId = ca.labId" + " and cu.id= ?1 " + " and ca.isBind!='1'";
    EntityManager em = entityManagerFactory.createEntityManager();
    try {
      Query query = em.createQuery(sql);
      query.setParameter(1, customerId);
      list = query.getResultList();
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      em.close();
    }
    return list;
  }
  
  /**
   * 
   * @author fanyb
   * @Description: TODO
   * @param customerId
   * @return List<Ca> 
   * @date Dec 2, 201510:47:51 AM
   *
   * @修改人 
   * @修改日期
   */
  public List<Ca> findByCustomerIdAll(String customerId) {
    List<Ca> list = null;
    Map<String,Object> paraMap = new HashMap<String,Object>();
    String sql ="select ca from Ca ca,CaCustomer cacu,Customer cu where "
        + "cu.id = cacu.customerId and cacu.labId = ca.labId and cu.id=:customerId";
    paraMap.put("customerId", customerId);
    try{
      list = queryObject(sql,paraMap);
    }catch(Exception ex){
      ex.printStackTrace();
    }
    return list;
  }

  /**
   * 
   * @author: huanghj
   * @Description: 获得该用户注册时间戳
   * @param @param libId
   * @param @return
   * @return long
   * @date 2015年10月24日下午2:43:09
   *
   * @修改人
   * @修改日期
   */
  public long getUserCaCreatTime(String libId) {
    String sql = "select create_time from tb_ca where lab_id='"+libId+"'";
   
    List<Map> obj = find(sql);
    if (obj != null && obj.size() > 0)
      return Long.valueOf(obj.get(0).get("create_time").toString());
    return 0;
  }
  
  public long getUserCaEndTime(String libId) {
    String sql = "select auth_end_time from tb_ca where lab_id='"+libId+"'";
    List<Map> obj = find(sql);
    if (obj != null && obj.size() > 0)
      return Long.valueOf(obj.get(0).get("auth_end_time").toString());
    return 0;
  }
 
  public List find(String sql) {
    List<Map> objList = null;
    EntityManager em = entityManagerFactory.createEntityManager();
    try {
      Query query = em.createNativeQuery(sql);
      query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
      objList = query.getResultList();
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      em.close();
    }
    return objList;
  }
}
